<template>
  <div style="margin: 20px">
    <div
      style="display: flex; justify-content: space-between; font-size: 16px; border-bottom: 1px solid #ccc; padding-bottom: 5px">
      <div>
        <span class="el-icon-tickets" style="margin-right: 15px"></span>
        <span>设备管理</span>
      </div>
      <div class="top-button">
        <el-button size="mini" @click="headSave()">保存</el-button>
        <el-button size="mini" @click="headSave('cancel')">保存并返回</el-button>
        <el-button size="mini" @click="headCancel">取消</el-button>
      </div>
    </div>

    <div style="margin: 10px 20px">
      <el-form :rules="rules" ref="ruleForm" :inline="true" :model="dataForm" label-width="100px" class="product-form">
        <el-row>
          <el-col :span="8">
            <el-form-item label="设备名称:" prop="equipmentName">
              <el-input v-model="dataForm.equipmentName" :disabled="readOnly" size="small" style="width: 100%;"
                        placeholder="请输入设备名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="设备编码:" prop="equipmentCode">
              <el-input v-model="dataForm.equipmentCode" :disabled="readOnly" size="small"
                        placeholder="请输入设备编码"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否启用:" prop="isEnable">
              <el-switch
                v-model="dataForm.isEnable"
                active-text="已启用"
                :disabled="true"
                size="small"
                :active-value="1"
                :inactive-value="0"
                inactive-text="未启用">
              </el-switch>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="产品名称:" prop="productName">
              <el-input
                v-model="dataForm.productName"
                size="small"
                :disabled="readOnly"
                :readonly="true"
                @click.native="headSelectProduct"
                placeholder="请选择产品">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产品编码:" prop="productCode">
              <el-input v-model="dataForm.productCode" :readonly="true" :disabled="readOnly" size="small"
                        placeholder="产品选择后自动带出"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="协议类型:" prop="agreementType">
              <el-input v-model="dataForm.agreementType" :readonly="true" :disabled="this.$route.query.type!=='add'"
                        size="small" placeholder="产品选择后自动带出"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="产品图片:">
              <el-upload
                :action="uploadPath"
                list-type="picture-card"
                :on-remove="handleRemove"
                :on-preview="handlePictureCardPreview"
                :on-success="handleSuccess"
                :on-exceed="handleExceed"
                :limit="1"
                :show-file-list="true"
                :file-list="fileList"
                :headers="headers"
                :disabled="type == 'view'"
                accept=".jpeg, .jpg, .png">
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>

          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16" class="remark">
            <el-form-item label="备注:">
              <el-input type="textarea" v-model="dataForm.remark" :disabled="readOnly" maxlength="500"
                        placeholder="请输入备注" show-word-limit></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>


    <el-tabs v-model="activeName" @tab-click="handleClickTab">
      <el-tab-pane label="点位信息" name="point">
        <div
          style="display: flex; justify-content: space-between; font-size: 16px; border-bottom: 1px solid #ccc; padding-bottom: 5px">
          <div>
            <span class="el-icon-tickets" style="margin-right: 15px"></span>
            <span>点位信息</span>
          </div>
          <div>
            <el-button v-if="!readOnly" size="mini" @click="headAdd()">新增</el-button>
          </div>
        </div>
        <el-row style="margin-top: 25px" :gutter="20">
          <div class="point-DA point-card">
            <el-col :span="6" v-for="(item, index) in tableData" :key="index">
              <el-card shadow="hover" style="font-size: 14px">
                <div class="point-head" style="position: relative;font-size: 20px; margin-bottom: 10px">
                  {{ item.pointName }}
                  <span
                    :style="{
						  			display: 'inline-block',
						  			height: '8px',
						  			width: '8px',
										background: item.isEnable === 1 ? 'rgb(10, 191, 91)' : 'rgb(229, 69, 69)',
						  			borderRadius: '7px',
						  			verticalAlign: 'middle',
						  			marginLeft: '10px',
						  			marginBottom: '5px'}">
              </span>
                  <el-tooltip class="item" v-if="!readOnly" effect="dark" content="编辑" placement="top">
                    <a style="font-size: 14px; position: absolute; right: 0" @click="rowEdit(item)">
                      <span class="el-icon-edit" style="font-size: 18px;color: #1677FF"></span>
                    </a>
                  </el-tooltip>
                </div>
                <div class="point-content" style="margin-bottom: 5px">
                  <div style="margin: 16px 6px 0 6px">
                    <span style="color: #646a73">点位编码：</span>
                    <span style="color: #1677ff">{{ item.pointCode }}</span>
                  </div>
                  <div style="margin: 16px 6px 0 6px">
                    <span style="color: #646a73">创建时间：</span>
                    <span style="color: #1677ff">{{ parseTime(item.createTime) }}</span>
                  </div>
                </div>
                <el-divider v-if="!readOnly"></el-divider>
                <div style="margin-top: 5px; float: right">
                  <div v-if="!readOnly">
                    <el-button
                      size="mini"
                      type="primary"
                      @click="rowRemove(item)"
                      style="margin: 5px"
                    >删除
                    </el-button>
                  </div>
                </div>
              </el-card>
            </el-col>
          </div>
        </el-row>

        <div class="block" style="float: right;" v-if="page.total !== 0">
          <el-pagination
            background
            :current-page="page.currentPage"
            :page-sizes="[8, 16, 32, 64, 128]"
            :page-size="page.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="page.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange">
          </el-pagination>
        </div>
      </el-tab-pane>
      <el-tab-pane label="告警配置" v-if="type != 'add'" name="config">
        <div style="margin-top: 5px">
          <el-form ref="gridHeadLayout" :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item>
              <el-input
                v-model="formInline.warningName"
                size="mini"
                placeholder="请输入告警配置名称">
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-select v-model="formInline.isEnable" size="mini" placeholder="请选择是否启用">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item class="top-button">
              <el-button size="mini" icon="el-icon-search" @click="handleSearch"></el-button>
              <el-button size="mini" icon="el-icon-refresh-right" @click="handleEmpty"></el-button>
            </el-form-item>
          </el-form>
        </div>

        <div>
          <el-table
            ref="warningConfigTable"
            border
            height="calc(100vh - 285px)"
            :data="configTable"
            tooltip-effect="dark"
            style="width: 100%;">
            <el-table-column
              type="index"
              label="序号"
              align="center"
              width="80"
              :index="indexMethod">
            </el-table-column>
            <el-table-column
              label="告警名称"
              align="center"
              prop="warningName"
              show-overflow-tooltip>
              <template slot-scope="scope">
                <el-tag>
                  {{ scope.row.warningName }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              prop="pointName"
              label="点位名称"
              align="center"
              show-overflow-tooltip>
              <template slot-scope="scope">
                <el-tag>
                  {{ scope.row.pointName }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              prop="priority"
              label="优先级"
              align="center"
              show-overflow-tooltip>
              <template slot-scope="scope">
                <el-tag type="danger" v-if="scope.row.priority == 3">
                  <dict-tag :type="DICT_TYPE.WARNING_PRIORITY" :value="scope.row.priority" />
                </el-tag>
                <el-tag type="warning" v-if="scope.row.priority == 2">
                  <dict-tag :type="DICT_TYPE.WARNING_PRIORITY" :value="scope.row.priority" />
                </el-tag>
                <el-tag type="success" v-if="scope.row.priority == 1">
                  <dict-tag :type="DICT_TYPE.WARNING_PRIORITY" :value="scope.row.priority" />
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              prop="createTime"
              label="创建时间"
              align="center"
              show-overflow-tooltip>
              <template v-slot="scope">
                <el-tag>
                  <span>{{ parseTime(scope.row.createTime) }}</span>
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              prop="isEnable"
              label="状态"
              align="center"
              show-overflow-tooltip>
              <template slot-scope="scope">
                <el-tag type="success" v-if="scope.row.isEnable == 1">
                  <dict-tag :type="DICT_TYPE.IS_ENABLE" :value="scope.row.isEnable"/>
                </el-tag>
                <el-tag type="danger" v-if="scope.row.isEnable == 0">
                  <dict-tag :type="DICT_TYPE.IS_ENABLE" :value="scope.row.isEnable"/>
                </el-tag>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
            background
            :current-page="configPage.currentPage"
            :page-sizes="[10, 20, 30, 50,100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="configPage.total"
            :page-size="configPage.pageSize"
            :pager-count="5"
            @size-change="changeSize"
            @current-change="changeCurrent"
            style="float: right; margin: 20px 0;">
          </el-pagination>
        </div>
      </el-tab-pane>
    </el-tabs>


    <point-information-dialog
      ref="pointDialog"
      @restOnLoad="restOnLoad"
    ></point-information-dialog>
    <opcda-dialog
      ref="opdc"
      @restOnLoad="restOnLoad">
    </opcda-dialog>
    <!--  选择产品  -->
    <SelectProductDialog
      ref="productDialog"
      @select-product="selectProduct"
    ></SelectProductDialog>
  </div>
</template>

<script>
import {detail, submit} from "@/api/cps/equipment-api";
import {coveragePoint, page as getPage, remove} from "@/api/cps/equipment-point-api"
import {page as getConifgPage} from "@/api/warning/warning-api"
import SelectProductDialog from "@/views/cps/equipment/components/SelectProductDialog.vue";
import {DICT_TYPE} from "@/utils/dict";
import OpcdaDialog from '@/views/cps/equipment/components/OpcdaDialog.vue'
import {getAccessToken} from "@/utils/auth";

export default {
  name: 'equipment',
  computed: {
    DICT_TYPE() {
      return DICT_TYPE
    }
  },
  components: {
    SelectProductDialog,
    OpcdaDialog,
  },
  data() {
    return {
      options: [],
      title: '设备新增',
      type: "view",
      activeName: "point",
      readOnly: false,
      tableLoading: true,
      formInline: {}, // 过滤条件
      // 用于判断是否超出容器
      isTextOverflow: false,
      tableData: [],
      configTable: [], // 配置列表
      fileList: [],
      uploadPath: process.env.VUE_APP_BASE_API + '/admin-api/infra/file/upload',
      headers: {Authorization: "Bearer " + getAccessToken()}, // 设置上传的请求头部
      productPoint: [],
      rules: {
        equipmentName: [
          {
            required: true,
            message: "请输入设备名称",
            trigger: ["blur", "change"],
          }
        ],
        productName: [
          {
            required: true,
            message: "请点击选择产品按钮",
            trigger: ["blur", "change"],
          }
        ],
        equipmentCode: [
          {
            required: true,
            message: "请输入设备编码",
            trigger: ["blur", "change"],
          }
        ],
      },
      dataForm: {},
      page: {
        pageSize: 8,
        currentPage: 1,
        total: 0,
      },
      configPage: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
    }
  },
  async created() {
    let {id, type} = this.$route.query;
    this.type = type;
    if (["edit"].includes(this.type)) {
      this.dataForm.id = id;
      this.title = "设备编辑";
      this.initData();
      this.onLoad(this.page);
      this.configOnload(this.configPage, {})
    }
    if (["view"].includes(this.type)) {
      this.dataForm.id = id;
      this.readOnly = true;
      this.title = "设备查看";
      this.initData();
      this.onLoad(this.page);
      this.configOnload(this.configPage, {})
    }
  },
  mounted() {
    this.options = this.$store.state.dict.dictDatas.is_enable
    const type = this.$route.query.type;
    if (type === 'add') {
      this.$tab.updatePage(Object.assign({}, this.$route, {title: '设备新增'}));
    } else if (type === 'edit') {
      this.$tab.updatePage(Object.assign({}, this.$route, {title: '设备编辑'}));
    } else {
      this.$tab.updatePage(Object.assign({}, this.$route, {title: '设备查看'}));
    }
  },
  methods: {
    //文件上传个数
    handleExceed(files, fileList) {
      this.$message.warning(`只能上传一个文件`);
    },
    handleSuccess(response, file, fileList) {
      this.dataForm.image = response.data
    },
    handlePictureCardPreview(file) {
      this.dataForm.image = file.url
    },
    handleRemove(file, fileList) {
      this.dataForm.image = ""
    },
    handleSearch () {
      this.configPage.currentPage = 1
      this.configOnload(this.configPage, this.formInline)
    },
    handleEmpty () {
      this.formInline = {}
      this.configOnload(this.configPage, {})
    },
    handleClickTab(tab) {
      this.activeName = tab.name
      this.configOnload(this.configPage, {})
    },
    indexMethod (index) {
      return index + 1
    },
    changeSize (val) {
      this.configPage.pageSize = val
      this.configOnload(this.configPage, {})
    },
    changeCurrent (val) {
      this.configPage.currentPage = val
      this.configOnload(this.configPage, {})
    },
    restOnLoad() {
      this.onLoad(this.page);
    },
    headAdd() {
      if (!this.dataForm.id) {
        this.$message.warning("请先保存设备信息");
        return;
      }
      this.$refs.opdc.addPoint(this.dataForm.id);
    },
    // 选择产品
    selectProduct(data) {
      this.dataForm.image = ''
      this.fileList = []
      this.$set(this.dataForm, 'agreementType', data.agreementType)
      this.$set(this.dataForm, 'productCode', data.productCode)
      this.$set(this.dataForm, 'productName', data.productName)
      this.$set(this.dataForm, 'stationAddress', data.stationAddress)
      this.$set(this.dataForm, 'image', data.image)
      this.headSave("product", data.id);
    },
    coveragePoint(equipmentId, productId) {
      coveragePoint(equipmentId, productId).then(() => {
        this.onLoad(this.page);
         this.$message({
          type: "success",
          message: "操作成功",
        });
      });
    },
    initData() {
      detail(this.dataForm.id).then((res) => {
        this.dataForm = res.data;
        if (res.data.image !== "" && res.data.image !== null && res.data.image !== undefined) {
          let file = {url: res.data.image}
          this.fileList.push(file)
        }
      });
    },
    headCancel() {
      this.$router.back();
    },
    headSave(type, productId) {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          this.$loading();
          submit(this.dataForm)
            .then((res) => {
              const {data, code} = res
              if (code === 0) {
                this.$message.success(
                  "操作成功"
                );
              } else {
                this.$message.success(msg);
              }
              if (type === "cancel") {
                this.$router.back();
              } else {
                //刷新数据
                Object.assign(this.dataForm, data);
                this.dataForm = data;
                this.initData();
                this.type = "edit";
                if (type === "product") {
                  this.coveragePoint(this.dataForm.id, productId);
                }
              }
            })
            .finally(() => {
              this.$loading().close();
            });
        }
      })
    },
    // 选择产品
    headSelectProduct() {
      if (["add"].includes(this.type)) {
        this.$confirm("选择产品后，设备信息将会保存", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          this.$refs.productDialog.openDialog();
        });
      } else {
        this.$confirm("重新选择产品后，点位信息将会被覆盖", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          this.$refs.productDialog.openDialog();
        });
      }
    },
    rowEdit(row) {
      this.$refs.opdc.editPoint(row);
    },
    rowRemove(row) {
      this.$confirm("确定删除数据", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功",
          });
        });
    },
    configOnload(page, params = {}) {
      if (this.dataForm.id === undefined) {
        return
      }
      this.page = page;
      this.tableLoading = true;
      params.equipmentId = this.dataForm.id
      getConifgPage(page.currentPage, page.pageSize, params).then(res => {
        const data = res.data
        this.configTable = data.records
        this.configPage.total = data.total
        this.tableLoading = false;
      })
    },
    onLoad(page, params = {}) {
      this.page = page;
      if (this.dataForm.id) {
        params.equipmentId = this.dataForm.id;
      }
      getPage(page.currentPage, page.pageSize, params).then((res) => {
        const data = res.data;
        this.page.total = data.total;
        this.tableData = data.records;
      });
    },
    handleSizeChange(val) {
      this.page.pageSize = val;
      this.onLoad(this.page);
    },
    handleCurrentChange(val) {
      this.page.currentPage = val;
      this.onLoad(this.page);
    },
  }
}
</script>

<style scoped lang="scss">
.point-card ::v-deep .el-card__body {
  padding: 15px 20px 5px 20px !important;
}

.point-card ::v-deep .el-divider--horizontal {
  margin: 0;
}

.top-button ::v-deep .el-button + .el-button {
  margin-left: 0;
}

.product-form ::v-deep .el-textarea__inner {
  resize: none;
  min-height: 111.6px !important;
}

.product-form ::v-deep .el-form-item {
  width: 100%;
}

.product-form ::v-deep .el-form-item__content {
  width: calc(100% - 100px);
}

.product-form ::v-deep .el-form-item__label {
  color: #3f4448;
  font-weight: 400;
}

.cardBigBox {
  width: calc(100% - 24px);
  padding: 12px;
  display: flex;
  flex-wrap: wrap;
  overflow: auto;
  background-color: #ffffff;
  align-content: flex-start;

  .cardbox {
    width: 24%;
    box-shadow: 0 0 5px #dde9ef;
    border: 1px solid #e7eff3;
    border-radius: 10px;
    margin: 16px 6px 0 6px;
    cursor: pointer;

    .cardTop {
      padding: 16px;

      .topContent {
        .instruction {
          white-space: nowrap; /* 防止文本换行 */
          overflow: hidden; /* 隐藏超出容器的文本 */
          text-overflow: ellipsis; /* 用省略号表示被截断的文本 */
          cursor: pointer; /* 当鼠标悬停时显示手形光标，提示用户有tooltip */
          font-size: 20px;
          color: #333;
        }

        .topItem {
          font-size: 15px;
          color: #666;
          line-height: 30px;
        }
      }
    }

    .cardBottom {
      font-size: 14px;
      line-height: 25px;
      display: flex;
      border-top: 1px solid #dcdfe6;
      justify-content: space-between;

      .topBottom {
        display: flex;
        align-items: center;
        justify-content: space-between;
        flex: 1;

        .statusContent {
          display: flex;
          align-items: center;

          .iconCard {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background-color: red;
            margin: 10px 6px;
          }
        }
      }
    }
  }
}

.block {
  //position: absolute;
  bottom: 0;
  width: calc(100% - 48px);
  padding: 12px 24px;
  background-color: #ffffff;
  display: flex;
  flex-direction: row-reverse;
}
</style>
